package com.base.message.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.base.common.ConfigConstants;
import com.base.common.datesource.MultipleDataSource;
import com.base.common.enums.MessageType;
import com.base.common.persistent.dao.MessageMapper;
import com.base.common.persistent.model.Message;
import com.base.message.service.MessageService;

/**
 * 通知信息等service的实现
 * 
 * @author Administrator
 *
 */
@Service("messageService")
public class MessageServiceImpl implements MessageService {

	@Resource
	private MessageMapper messageMapper;

	@Override
	public List<Message> getMessages(int page, int messageType, int compoundsId) {
		List<Message> messagerList = new ArrayList<Message>();
		try {
			// 根据通知类型获取字段名
			String field = null;
			switch (messageType) {
			case 0:
				field = MessageType.VILLAGE.getDatebaseField();
				break;
			case 1:
				field = MessageType.SPECIAL.getDatebaseField();
				break;
			case 2:
				field = MessageType.GOVERNMENT.getDatebaseField();
				break;
			case 3:
				field = MessageType.TRAINING.getDatebaseField();
				break;
			default:
				return messagerList;
			}

			// 查询文章类型模块id
			int typeId = messageMapper.queryTypeIdByCompoundsIdAndField(
					compoundsId, field);

			System.out.println("--------------------:" + typeId);
			messagerList = testMysqlConnection((page - 1) * 15, page * 15,
					typeId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		MultipleDataSource.setDataSourceKey("sqlserverDataSource");
		return messagerList;
	}

	public List<Message> testMysqlConnection(int start, int end, int typeId) {
		List<Message> messages = new ArrayList<Message>();
		try {
			
			
			MultipleDataSource.setDataSourceKey("mysqlDataSource");
			messages = messageMapper.test(start, end, typeId);
			for (Message message : messages) {
				int year = 1900 + message.getCreateDate().getYear();
				int month = message.getCreateDate().getMonth() + 1;
				int date = message.getCreateDate().getDate();
				String wyUrls = "http://" + ConfigConstants.SERVERNAME + "/"
						+ message.getWyUrls() + "/" + year + "/"
						+ (month < 10 ? ("0" + month) : month)
						+ (date < 10 ? ("0" + date) : date) + "/"
						+ message.getId() + ".html";
				message.setWyUrls(wyUrls);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return messages;

	}
}
